//
//  AXShoppingCartViewController.m
//  hwacdx 购物车界面
//
//  Created by hwacdx on 2019/4/30.
//  Copyright © 2019 hwacdx. All rights reserved.
//

#define kBottomBarHeight 50
#define kSectionHeaderHeight 40

#import "AXShoppingCartViewController.h"
#import "AXShoppingCartTableViewCell.h"
#import "AXShoppingCartBottomBar.h"
#import "AXShoppingCartInvalidHeaderView.h"
#import "AXShoppingCartHeaderView.h"

#import "AXShoppingCartStore.h"

@interface AXShoppingCartViewController ()<UITableViewDelegate, UITableViewDataSource, AXShoppingCartTableViewCellDelegate, AXShoppingCartBottomBarDelegate, AXShoppingCartInvalidHeaderViewDelegate, AXShoppingCartHeaderViewDelegate>

@property (strong, nonatomic) UITableView *tableView;

/**
 有效商品的数据源
 */
@property (strong, nonatomic) NSMutableArray *validDataSource;

/**
 无效商品的数据源
 */
@property (strong, nonatomic) NSMutableArray *invalidDataSource;

/**
 底部的全选、结算工具条
 */
@property (strong, nonatomic) AXShoppingCartBottomBar *bottomBar;

/**
 已选中的商品
 */
@property (strong, nonatomic) NSMutableArray *selectedItems;

/**
 已创建的 headerView
 */
@property (strong, nonatomic) NSMutableArray *headerViewArray;

/**
 导航栏右侧按钮
 */
@property (strong, nonatomic) UIBarButtonItem *rightBtnItem;
@property (strong, nonatomic) UIBarButtonItem *leftBtnItem;

/**
 是否为编辑状态
 */
@property (nonatomic) BOOL isEditing;
@property (nonatomic) NSInteger editGoodsIndex;
@property (nonatomic) NSInteger bottomBarY;
@property (nonatomic) NSInteger tableViewY;
@property (nonatomic) NSInteger tableViewHeight;

@end

@implementation AXShoppingCartViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"购物车";
    //解决在 iOS 9 UITableViewWrapperView 向下偏移的情况
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor lightGrayColor];
    self.tableViewY = kTOPBAR_HEIGHT + kCommonViewMargin_10;
    self.bottomBarY = kScreenHeight - kBottomBarHeight - kBOTTOM_SPACE;
    self.tableViewHeight = kScreenHeight - kBottomBarHeight - self.tableViewY;
    [self.view addSubview:self.tableView];
    [self configDataSource];
    [self addNavItem];
}

- (void)addNavItem{
    self.leftBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"重置" style:UIBarButtonItemStylePlain target:self action:@selector(leftItemAction)];
    self.navigationItem.leftBarButtonItem = self.leftBtnItem;
    
    self.rightBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(rightItemAction)];
    self.navigationItem.rightBarButtonItem = self.rightBtnItem;
}

- (void)leftItemAction{
    [self configDataSource];
}

- (void)rightItemAction{
    
    //清空选中的商品，刷新 bottomBar
    self.bottomBar.isAllSelected = NO;
    [self.selectedItems removeAllObjects];
    
    if (self.isEditing) {//编辑 -> 未编辑
        self.isEditing = NO;
        [self.rightBtnItem setTitle:@"编辑"];
        //重新计算总价
        [self handleTotalPrice];
        
    } else {//未编辑 -> 编辑
        self.isEditing = YES;
        [self.rightBtnItem setTitle:@"完成"];
    }
    
    //重置所有店铺的全选状态
    for (AXShoppingCartHeaderView *headerView in self.headerViewArray) {
        headerView.isSelected = NO;
    }
    
    [self.bottomBar setIsEditing:self.isEditing];
    [self.tableView reloadData];
}

//添加底部的全选、结算工具条
- (void)configBottomBar{
    if (!self.bottomBar) {
        self.bottomBar = [[NSBundle mainBundle] loadNibNamed:@"AXShoppingCartBottomBar" owner:nil options:nil][0];
        self.bottomBar.frame = CGRectMake(0, self.bottomBarY, kScreenWidth, kBottomBarHeight);
        self.bottomBar.delegate = self;
        [self.view addSubview:self.bottomBar];
    } else {
        self.bottomBar.hidden = NO;
    }
    
    [self configNavRightBtnItem];
    [self.bottomBar setIsEditing:self.isEditing];
}

- (void)configNavRightBtnItem{
    //点击了全选按钮之后，在其他界面添加了购物车
    if (self.bottomBar.isAllSelected) {
        [self.selectedItems removeAllObjects];
        //把所有的商品选中
        for (AXShoppingCartStore *store in self.validDataSource) {
            [self.selectedItems addObjectsFromArray:store.goodsList];
        }
        
        //重新计算总价
        [self handleTotalPrice];
    }
    
    if (self.isEditing) {//编辑 -> 未编辑
        [self.rightBtnItem setTitle:@"完成"];
    } else {//未编辑 -> 编辑
        [self.rightBtnItem setTitle:@"编辑"];
    }
    
    //self.rightBtnItem.hidden = NO;
}

- (UITableView *)tableView{
    if (!_tableView) {         
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.tableViewY, kScreenWidth, self.tableViewHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        //_tableView.separatorColor = kColorSeparator;
        _tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.tableFooterView = [UIView new];
        _tableView.backgroundColor = [UIColor clearColor];
        [_tableView registerNib:[UINib nibWithNibName:@"AXShoppingCartTableViewCell" bundle:nil] forCellReuseIdentifier:@"CartCell"];
    }
    return _tableView;
}

- (NSMutableArray *)validDataSource{
    if (!_validDataSource) {
        _validDataSource = [NSMutableArray array];
    }
    return _validDataSource;
}

- (NSMutableArray *)headerViewArray{
    if (!_headerViewArray) {
        _headerViewArray = [NSMutableArray array];
    }
    return _headerViewArray;
}

- (NSMutableArray *)invalidDataSource{
    if (!_invalidDataSource) {
        _invalidDataSource = [NSMutableArray array];
    }
    return _invalidDataSource;
}

- (NSMutableArray *)selectedItems{
    if (!_selectedItems) {
        _selectedItems = [NSMutableArray array];
    }
    return _selectedItems;
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.invalidDataSource.count > 0) {//有无效商品
        return self.validDataSource.count + 1;
    } else {//没有无效商品
        return self.validDataSource.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == self.validDataSource.count) {//无效商品
        return self.invalidDataSource.count;
    } else {//有效商品        
        AXShoppingCartStore *store = self.validDataSource[section];
        return store.goodsList.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 110;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return kSectionHeaderHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return kCommonViewMargin_10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AXShoppingCartTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CartCell"];
    cell.delegate = self;
    cell.indexPath = indexPath; 
    
    if (indexPath.section == self.validDataSource.count) {//无效商品
        AXHomeGoods *goods = self.invalidDataSource[indexPath.row];
        [cell setGoods:goods valid:NO];
        
    } else {//有效商品
        //取出数据模型
        AXShoppingCartStore *store = self.validDataSource[indexPath.section];
        AXHomeGoods *goods = store.goodsList[indexPath.row];
        [cell setGoods:goods valid:YES];
        
        // 已点击全选、cell 已选中
        if (self.bottomBar.isAllSelected || [self.selectedItems containsObject:goods]) {
            cell.isSelected = YES;
        } else {
            cell.isSelected = NO;
        }
    }
 
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section == self.validDataSource.count) {// 此 section 显示的是无效商品
        AXShoppingCartInvalidHeaderView *view = [[AXShoppingCartInvalidHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
        view.delegate = self;
        return view;
    }
        
    //此 section 显示的是有效商品
    if (self.headerViewArray.count > section) {//此 section 的 headerView 已创建
        AXShoppingCartHeaderView *headerView = self.headerViewArray[section];
        if (self.bottomBar.isAllSelected) {//bottomBar 的全选状态:YES，设置店铺的全选状态
            headerView.isSelected = YES;
        }
        return headerView;
        
    } else {//此 section 的 headerView 未创建
        AXShoppingCartStore *store = self.validDataSource[section];
        AXShoppingCartHeaderView *headerView = [[NSBundle mainBundle] loadNibNamed:@"AXShoppingCartHeaderView" owner:nil options:nil][0];
        headerView.frame = CGRectMake(0, 0, kScreenWidth, kSectionHeaderHeight);
        headerView.storeName = store.supplierName;
        headerView.section = section;
        headerView.delegate = self;
        [self.headerViewArray addObject:headerView];
        return headerView;
    }
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self deleteDataWithSelectedItems:nil indexPath:indexPath];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.isEditing){
        return YES;
    }
    return NO;
}

#pragma mark - AXShoppingCartTableViewCellDelegate
- (void)shoppingCartTableViewCell_buttonActionAtIndexPath:(NSIndexPath *)indexPath tag:(NSInteger)tag goodsNum:(nonnull NSString *)goodsNum{
    
    AXShoppingCartStore *store = self.validDataSource[indexPath.section];
    AXHomeGoods *goods = store.goodsList[indexPath.row];

    if (tag == 112) {//修改商品数量
        goods.number = [goodsNum integerValue];
        //取出旧的商品数组
        NSMutableArray *goodsList = [NSMutableArray arrayWithArray:store.goodsList];
        [goodsList replaceObjectAtIndex:indexPath.row withObject:goods];
        //替换新的商品数组
        store.goodsList = goodsList;
        [self.validDataSource replaceObjectAtIndex:indexPath.section withObject:store];
        //计算商品价格
        [self handleTotalPrice];
        return;
    }
    
    // kShoppingCartBottomBarAllSelectBtnTag (勾选商品)
    if ([self.selectedItems containsObject:goods]) {//已选中 -> 取消选中
        [self.selectedItems removeObject:goods];
        //取消店铺全选
        AXShoppingCartHeaderView *headerView = self.headerViewArray[indexPath.section];
        headerView.isSelected = NO;
        
    } else {//未选中 -> 选中
        [self.selectedItems addObject:goods];
        BOOL isAllSelected = YES;
        
        //取出当前选中的店铺商品
        AXShoppingCartStore *store = self.validDataSource[indexPath.section];
        for (AXHomeGoods *goods in store.goodsList) {
            if (![self.selectedItems containsObject:goods]) {//未全选（单个店铺)
                isAllSelected = NO;
            }
        }
        
        if (isAllSelected) {//已全选（单个店铺)
            AXShoppingCartHeaderView *headerView = self.headerViewArray[indexPath.section];
            headerView.isSelected = YES;
        }
    }
    
    //判断所有的店铺是否已全选
    [self judgeAllStoreIsSelected];
    
    //计算商品价格
    [self handleTotalPrice];
    [self.bottomBar setIsEditing:self.isEditing];
    [self.tableView reloadData];
}

- (void)shoppingCartHeaderView_buttonActionAtSection:(NSInteger)section isSelected:(BOOL)isSelected{
   
    //点击了店铺全选按钮
    AXShoppingCartStore *store = self.validDataSource[section];
    if (isSelected) {//已全选（单个店铺）
        for (AXHomeGoods *goods in store.goodsList) {
            if (![self.selectedItems containsObject:goods]) {//不包含此商品
                [self.selectedItems addObject:goods];
            }
        }
        
        //判断所有的店铺是否已全选
        [self judgeAllStoreIsSelected];
        
    } else {//取消全选（单个店铺）
        [self.selectedItems removeObjectsInArray:store.goodsList];
        [self.bottomBar setIsAllSelected:NO];
    }
    
    //计算商品价格
    [self handleTotalPrice];
    [self.bottomBar setIsEditing:self.isEditing];
    [self.tableView reloadData];
}

#pragma mark - AXShoppingCartBottomBarDelegate
- (void)shoppingCartBottomBar_buttonActionAtTag:(NSInteger)tag{
    
    if (tag == 111) {//点击全选按钮
        //全选、取消全选都要清空数组
        [self.selectedItems removeAllObjects];
        
        if (self.bottomBar.isAllSelected) {//已全选（所有的店铺商品）
            //把所有的商品选中
            for (AXShoppingCartStore *store in self.validDataSource) {
                [self.selectedItems addObjectsFromArray:store.goodsList];
            }
            
        } else {//取消全选（所有的店铺商品）
            //重置店铺的全选状态
            for (AXShoppingCartHeaderView *headerView in self.headerViewArray) {
                headerView.isSelected = NO;
            }
        }
        
        if(self.isEditing){//编辑状态(删除)
           
        } else {
            //计算商品价格
            [self handleTotalPrice];
        }
        
        [self.tableView reloadData];
        
    } else {
        
        if (self.selectedItems.count == 0) {//未选中商品
            return;
        }
        
        if(self.isEditing){//编辑状态(点击了删除按钮)
            [self deleteDataWithSelectedItems:self.selectedItems indexPath:nil];
            
        } else {//点击了结算按钮
            
        }
    }
}

#pragma mark - 计算商品总价
- (void)handleTotalPrice{
    CGFloat totalPrice = 0.0;
    for (AXHomeGoods *goods in self.selectedItems) {
        totalPrice += goods.price * goods.number;
    }
    
    self.bottomBar.priceText = [NSString stringWithFormat:@"%.2f", totalPrice];
    self.bottomBar.selectCount = self.selectedItems.count;
}

#pragma mark - 判断所有的店铺是否已全选
- (void)judgeAllStoreIsSelected{
    BOOL isAllSelected = YES;
    for (AXShoppingCartStore *store in self.validDataSource) {
        for (AXHomeGoods *goods in store.goodsList) {
            if (![self.selectedItems containsObject:goods]) {//不包含此商品
                isAllSelected = NO;//未全选（所有的店铺商品）
                break;//跳出两层 for 循环
            }
        }
    }
    
    //判断所有店铺是否已全选
    if (isAllSelected) {//已全选（所有的店铺商品）
        [self.bottomBar setIsAllSelected:YES];
    } else {//未全选（所有的店铺商品）
        [self.bottomBar setIsAllSelected:NO];
    }
}

#pragma mark - AXShoppingCartInvalidHeaderViewDelegate
- (void)shoppingCartInvalidHeaderView_buttonAction{
    //清空无效商品
    self.invalidDataSource = nil;
    [self.tableView reloadData];
}

//配置数据源
- (void)configDataSource{
    AXHomeGoods *goods = [[AXHomeGoods alloc] init];
    goods.name = @"红烧牛肉面";
    goods.price = 3.5;
    goods.number = 1;
    
    AXHomeGoods *goods2 = [[AXHomeGoods alloc] init];
    goods2.name = @"香辣牛肉面";
    goods2.price = 3.9;
    goods2.number = 1;
    
    AXShoppingCartStore *store = [[AXShoppingCartStore alloc] init];
    store.supplierName = @"康师傅旗舰店";
    store.goodsList = @[goods, goods2];
    
    AXHomeGoods *goods3 = [[AXHomeGoods alloc] init];
    goods3.name = @"小米移动电源2";
    goods3.price = 199;
    goods3.number = 1;
    
    AXHomeGoods *goods4 = [[AXHomeGoods alloc] init];
    goods4.name = @"小米蓝牙耳机 🎧";
    goods4.price = 399.99;
    goods4.number = 1;
    
    AXShoppingCartStore *store2 = [[AXShoppingCartStore alloc] init];
    store2.supplierName = @"小米天猫旗舰店";
    store2.goodsList = @[goods3, goods4];
    
    NSArray *storeList = @[store, store2];
    
    for (AXShoppingCartStore *store in storeList) {
        NSMutableArray *goodsList = [NSMutableArray arrayWithArray:store.goodsList];
        
        for (AXHomeGoods *goods in store.goodsList) {
            if ([goods.invalid isEqualToString:@"1"]) {//无效商品
                //1.添加到无效商品数组中
                [self.invalidDataSource addObject:goods];
                //2.1.移除无效商品
                [goodsList removeObject:goods];
                store.goodsList = goodsList;
            }
        }
        
        //2.2.添加有效商品到数组中
        [self.validDataSource addObject:store];
    }
    
    if (self.validDataSource.count > 0) {//有商品数据
        [self configBottomBar];
    } else {//无商品数据
        self.bottomBar.hidden = YES;
    }
  
    [self.tableView reloadData];
}

- (void)deleteDataWithSelectedItems:(NSArray *)selectedItems indexPath:(NSIndexPath *)indexPath{
    
    if (selectedItems && selectedItems.count > 0) {//批量删除单个/多个商品(有效商品)
        
        for (AXHomeGoods *goods in selectedItems) {
            for (int j = 0; j < self.validDataSource.count; j++) {
                AXShoppingCartStore *store = self.validDataSource[j];
                if ([store.goodsList containsObject:goods]) {//已遍历到选中的商品
                    NSMutableArray *goodsList = [NSMutableArray arrayWithArray:store.goodsList];
                    [goodsList removeObject:goods];
                    store.goodsList = goodsList;
                    
                    if(store.goodsList.count == 0){//该店铺已无商品
                        [self.validDataSource removeObject:store];
                        continue;
                    } else {//该店铺还有商品
                        [self.validDataSource replaceObjectAtIndex:j withObject:store];
                    }
                }
            }
        }
        
    } else {//滑动删除单个商品
        
        if (indexPath.section == self.validDataSource.count) {//无效商品
            [self.invalidDataSource removeObjectAtIndex:indexPath.row];
            
        } else {//有效商品
            AXShoppingCartStore *store = self.validDataSource[indexPath.section];
            NSMutableArray *goodsList = [NSMutableArray arrayWithArray:store.goodsList];
            [goodsList removeObjectAtIndex:indexPath.row];
            store.goodsList = goodsList;
            
            if(store.goodsList.count == 0){//该店铺已无商品
                [self.validDataSource removeObject:store];
            } else {//该店铺还有商品
                [self.validDataSource replaceObjectAtIndex:indexPath.section withObject:store];
            }
        }
    }
    
    if (self.validDataSource.count == 0) {
        //已删除所有的商品，隐藏 bottombar
        self.bottomBar.hidden = YES;
        self.isEditing = NO;
        //self.rightBtnItem.hidden = YES;
        [self.rightBtnItem setTitle:@"编辑"];
        [self.bottomBar setIsEditing:self.isEditing];
    }
 
    [self.selectedItems removeObjectsInArray:selectedItems];
    [self.tableView reloadData];
}

@end
